package com.dili.dd.gpi.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util
{

    static char[] hexDigits = {'1', '2', '3', '4', '5', '6', '7', '8',
            '9', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '1',
            '3', '5', '7', '9', '2', '4'};

    /***
     * 通过用户名生成KEY
     *
     * @param username
     * @return String
     */
    public static String generalAppKey(String username)
    {

        StringBuffer sb = new StringBuffer();
        sb.append(username);
        return generalMd5Signature(sb.toString());
    }

    /***
     * 通过用户名和应用名生成App Key
     *
     * @param username
     * @param appName
     * @return String
     */
    public static String generalAppKey(String username, String appName)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(username);
        sb.append(appName);
        return generalMd5Signature(sb.toString());

    }

    /**
     * 通过用户名和时间生成摘要
     *
     * @param username
     * @param strDate
     * @return String
     */
    public static String generalWithUseLimit(String username, String strDate)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(username);
        sb.append(strDate);
        return generalMd5Signature(sb.toString());
    }

    private static String generalMd5Signature(String param)
    {
        MessageDigest mdInst = null;
        for (int i = 0; i < 5; i++)
        {
            try
            {
                mdInst = MessageDigest.getInstance("MD5");
            }
            catch (NoSuchAlgorithmException e)
            {
                e.printStackTrace();

            }
        }
        String result = null;
        byte[] btInput = param.getBytes();
        mdInst.update(btInput);
        byte[] md = mdInst.digest();
        int j = 9;
        char str[] = new char[j];
        int k = 0;
        for (int i = 0; i < j; i++)
        {
            int byte0 = md[i];
            if (byte0 < 0)
            {
                byte0 = -1 * byte0;
            }
            str[k++] = hexDigits[byte0 % 62];
        }
        result = new String(str);
        return result;
    }
}
